package com.gxy.learn.thread.example;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @description:
 * @author: gaoxueyong
 * @Date: 2022/11/10 14:14
 */
public class LockTest {
    //    声明排他锁
    static Lock lock = new ReentrantLock();

    private static int num;
//    读写锁
    static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
//    读的时候运行其他线程读，不允许写
    static Lock readLock = readWriteLock.readLock();
//    写的时候不允许其他线程读和写
    static Lock writeLock = readWriteLock.writeLock();

    public static void read(Lock lock) {
        lock.lock();
        try {
            Thread.sleep(1000);
            System.out.println("read over!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void write(Lock lock, int v) {
        lock.lock();
        try {
            Thread.sleep(1000);
            num = v;
            System.out.println("write over!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
//        耗时20s
//        Runnable readRunable = () -> read(lock);
//        Runnable wrireRunable = ()->write(lock,1);

//        耗时3秒
        Runnable readRunable = () -> read(readLock);
        Runnable wrireRunable = ()->write(writeLock,1);
        for(int i=0;i<18;i++) new Thread(readRunable).start();
        for(int i=0;i<2;i++) new Thread(wrireRunable).start();
    }
}
